<!DOCTYPE html>
<html>
	<head>
		<title>订单售后处理</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css & js 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<script src="../../static/sa.js"></script>
		<style>
			/* 售后卡片样式 */
			.after-sale-card {
				border: 1px solid #ebeef5;
				border-radius: 8px;
				margin-bottom: 20px;
				overflow: hidden;
				background: white;
				transition: all 0.3s;
			}
			.after-sale-card:hover {
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
			}
			
			/* 卡片头部 */
			.card-header {
				padding: 15px 20px;
				background: #f8f9fa;
				border-bottom: 1px solid #ebeef5;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			.after-sale-id {
				font-size: 16px;
				font-weight: 500;
				color: #303133;
			}
			.after-sale-status {
				padding: 4px 12px;
				border-radius: 12px;
				font-size: 12px;
				font-weight: 500;
			}
			.status-pending { background-color: #E6A23C; color: white; }
			.status-processing { background-color: #409EFF; color: white; }
			.status-approved { background-color: #67C23A; color: white; }
			.status-rejected { background-color: #F56C6C; color: white; }
			.status-completed { background-color: #909399; color: white; }
			
			/* 卡片内容 */
			.card-content {
				padding: 20px;
			}
			.info-row {
				display: flex;
				margin-bottom: 15px;
				align-items: flex-start;
			}
			.info-label {
				width: 100px;
				color: #909399;
				font-size: 14px;
				flex-shrink: 0;
			}
			.info-value {
				flex: 1;
				color: #303133;
				font-size: 14px;
			}
			
			/* 商品信息 */
			.product-info {
				display: flex;
				gap: 15px;
				padding: 15px;
				background: #f8f9fa;
				border-radius: 6px;
				margin: 10px 0;
			}
			.product-image {
				width: 80px;
				height: 80px;
				border-radius: 6px;
				overflow: hidden;
			}
			.product-image img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
			.product-details {
				flex: 1;
			}
			.product-name {
				font-weight: 500;
				margin-bottom: 8px;
			}
			.product-price {
				color: #F56C6C;
				font-weight: 500;
			}
			
			/* 操作按钮 */
			.action-buttons {
				padding: 15px 20px;
				border-top: 1px solid #ebeef5;
				background: #fafafa;
				text-align: right;
			}
			
			/* 搜索面板 */
			.search-panel {
				background: white;
				padding: 20px;
				border-radius: 8px;
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
				margin-bottom: 20px;
			}
			
			/* 分页样式 */
			.page-box {
				text-align: center;
				margin-top: 20px;
			}
			
			/* 处理表单样式 */
			.process-form {
				max-width: 600px;
			}
			.process-form .el-textarea {
				margin-top: 10px;
			}
		</style>
	</head>
	<body>
		<div id="app" class="vue-box" style="padding: 20px;">
			<!-- 搜索面板 -->
			<div class="search-panel">
				<el-form :inline="true" size="small">
					<el-form-item label="售后单号">
						<el-input v-model="searchForm.afterSaleId" placeholder="请输入售后单号" clearable></el-input>
					</el-form-item>
					<el-form-item label="订单号">
						<el-input v-model="searchForm.orderId" placeholder="请输入订单号" clearable></el-input>
					</el-form-item>
					<el-form-item label="售后状态">
						<el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
							<el-option label="待处理" value="pending"></el-option>
							<el-option label="处理中" value="processing"></el-option>
							<el-option label="已同意" value="approved"></el-option>
							<el-option label="已拒绝" value="rejected"></el-option>
							<el-option label="已完成" value="completed"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="售后类型">
						<el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
							<el-option label="退款" value="refund"></el-option>
							<el-option label="退货退款" value="return_refund"></el-option>
							<el-option label="换货" value="exchange"></el-option>
							<el-option label="维修" value="repair"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
						<el-button type="info" icon="el-icon-refresh" @click="reset">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
			
			<!-- 售后列表 -->
			<div v-loading="loading">
				<div v-for="item in dataList" :key="item.id" class="after-sale-card">
					<!-- 卡片头部 -->
					<div class="card-header">
						<div class="after-sale-id">售后单号：{{ formatAfterSaleId(item.id) }}</div>
						<span :class="['after-sale-status', 'status-' + item.status]">
							{{ getStatusText(item.status) }}
						</span>
					</div>
					
					<!-- 卡片内容 -->
					<div class="card-content">
						<div class="info-row">
							<span class="info-label">关联订单：</span>
							<span class="info-value">{{ formatOrderId(item.orderId) }}</span>
						</div>
						<div class="info-row">
							<span class="info-label">售后类型：</span>
							<span class="info-value">{{ getTypeText(item.type) }}</span>
						</div>
						<div class="info-row">
							<span class="info-label">申请用户：</span>
							<span class="info-value">{{ item.user?.nickname || '未知用户' }} ({{ item.user?.phone || '无联系方式' }})</span>
						</div>
						<div class="info-row">
							<span class="info-label">申请原因：</span>
							<span class="info-value">{{ item.reason || '无' }}</span>
						</div>
						<div class="info-row">
							<span class="info-label">申请时间：</span>
							<span class="info-value">{{ item.createdAt }}</span>
						</div>
						<div class="info-row" v-if="item.adminReply">
							<span class="info-label">处理回复：</span>
							<span class="info-value">{{ item.adminReply }}</span>
						</div>
						<div class="info-row" v-if="item.processedAt">
							<span class="info-label">处理时间：</span>
							<span class="info-value">{{ item.processedAt }}</span>
						</div>
						
						<!-- 商品信息 -->
						<div class="info-row">
							<span class="info-label">相关商品：</span>
							<div class="info-value">
								<div class="product-info" v-if="item.product">
									<div class="product-image" v-if="item.product.images && item.product.images.length > 0">
										<img :src="getFullImageUrl(item.product.images[0].image_url)" :alt="item.product.name">
									</div>
									<div class="product-details">
										<div class="product-name">{{ item.product.name }}</div>
										<div class="product-price">￥{{ item.product.price }}</div>
										<div style="font-size: 12px; color: #909399;">数量: {{ item.quantity || 1 }}</div>
									</div>
								</div>
							</div>
						</div>
					</div>
					
					<!-- 操作按钮 -->
					<div class="action-buttons">
						<el-button size="small" @click="viewDetail(item)">查看详情</el-button>
						<el-button size="small" type="primary" @click="processAfterSale(item)" 
							v-if="item.status === 'pending' || item.status === 'processing'">处理</el-button>
						<el-button size="small" type="success" @click="completeAfterSale(item)" 
							v-if="item.status === 'approved'">完成</el-button>
					</div>
				</div>
				
				<!-- 空状态 -->
				<div v-if="!loading && dataList.length === 0" style="text-align: center; padding: 50px; color: #909399;">
					<i class="el-icon-document" style="font-size: 48px; margin-bottom: 16px;"></i>
					<p>暂无售后申请</p>
				</div>
			</div>
			
			<!-- 分页 -->
			<div class="page-box" v-if="dataCount > 0">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageInfo.pageNum"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="pageInfo.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="dataCount">
				</el-pagination>
			</div>
			
			<!-- 处理售后对话框 -->
			<el-dialog title="处理售后申请" :visible.sync="processDialogVisible" width="600px">
				<el-form :model="processForm" class="process-form" label-width="100px">
					<el-form-item label="处理结果">
						<el-radio-group v-model="processForm.action">
							<el-radio label="approve">同意</el-radio>
							<el-radio label="reject">拒绝</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="处理说明">
						<el-input type="textarea" v-model="processForm.reply" 
							placeholder="请输入处理说明..." :rows="4"></el-input>
					</el-form-item>
					<el-form-item label="退款金额" v-if="processForm.action === 'approve' && currentAfterSale.type === 'refund'">
						<el-input-number v-model="processForm.refundAmount" 
							:precision="2" :step="0.01" :max="currentAfterSale.maxRefundAmount || 0"></el-input-number>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="processDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitProcess" :loading="processLoading">确定</el-button>
				</div>
			</el-dialog>
		</div>
		
		<script>
			// 配置axios默认值
			axios.defaults.baseURL = 'http://localhost:8080';
			
			var app = new Vue({
				el: '#app',
				data: {
					loading: false,
					processLoading: false,
					searchForm: {
						afterSaleId: '',
						orderId: '',
						status: '',
						type: ''
					},
					pageInfo: {
						pageNum: 1,
						pageSize: 10
					},
					dataList: [],
					dataCount: 0,
					baseImageUrl: 'http://8.134.184.130:8008/images/',
					
					// 处理对话框
					processDialogVisible: false,
					currentAfterSale: {},
					processForm: {
						action: 'approve',
						reply: '',
						refundAmount: 0
					},
					
					// 状态和类型映射
					statusMap: {
						'pending': '待处理',
						'processing': '处理中', 
						'approved': '已同意',
						'rejected': '已拒绝',
						'completed': '已完成'
					},
					typeMap: {
						'refund': '退款',
						'return_refund': '退货退款',
						'exchange': '换货',
						'repair': '维修'
					}
				},
				methods: {
					// 搜索
					search() {
						this.loading = true;
						const params = {
							pageNum: this.pageInfo.pageNum,
							pageSize: this.pageInfo.pageSize,
							...this.searchForm
						};
						
						// 移除空值参数
						Object.keys(params).forEach(key => {
							if (params[key] === '' || params[key] === null || params[key] === undefined) {
								delete params[key];
							}
						});
						
						axios.get('/afterSale/listAfterSale', { params })
							.then(response => {
								if (response.data.code === 200) {
									this.dataList = response.data.data.list || [];
									this.dataCount = response.data.data.total || 0;
								} else {
									this.$message.error(response.data.message || '获取数据失败');
								}
							})
							.catch(error => {
								console.error('Error:', error);
								this.$message.error('获取数据失败');
								// 模拟数据用于演示
								this.loadMockData();
							})
							.finally(() => {
								this.loading = false;
							});
					},
					
					// 加载模拟数据
					loadMockData() {
						this.dataList = [
							{
								id: 1,
								orderId: 'ORDER0000001',
								type: 'refund',
								status: 'pending',
								reason: '商品质量问题，申请退款',
								createdAt: '2024-01-15 10:30:00',
								user: {
									nickname: '张三',
									phone: '13800138000'
								},
								product: {
									name: '苹果iPhone 15 Pro',
									price: 7999.00,
									images: [
										{ image_url: 'phone1.jpg' }
									]
								},
								quantity: 1,
								maxRefundAmount: 7999.00
							},
							{
								id: 2,
								orderId: 'ORDER0000002', 
								type: 'exchange',
								status: 'processing',
								reason: '收到商品颜色不对，需要换货',
								createdAt: '2024-01-14 15:20:00',
								adminReply: '正在处理中，请耐心等待',
								user: {
									nickname: '李四',
									phone: '13900139000'
								},
								product: {
									name: '华为Mate 60 Pro',
									price: 6999.00,
									images: [
										{ image_url: 'phone2.jpg' }
									]
								},
								quantity: 1
							}
						];
						this.dataCount = 2;
					},
					
					// 重置搜索
					reset() {
						this.searchForm = {
							afterSaleId: '',
							orderId: '',
							status: '',
							type: ''
						};
						this.pageInfo.pageNum = 1;
						this.search();
					},
					
					// 格式化售后单号
					formatAfterSaleId(id) {
						return 'AS' + String(id).padStart(8, '0');
					},
					
					// 格式化订单号
					formatOrderId(orderId) {
						if (!orderId) return '';
						if (String(orderId).toUpperCase().startsWith('ORDER')) {
							return String(orderId).toUpperCase();
						}
						const numPart = String(orderId).replace(/[^0-9]/g, '');
						return 'ORDER' + numPart.padStart(7, '0');
					},
					
					// 获取状态文本
					getStatusText(status) {
						return this.statusMap[status] || status;
					},
					
					// 获取类型文本
					getTypeText(type) {
						return this.typeMap[type] || type;
					},
					
					// 获取完整图片URL
					getFullImageUrl(imageUrl) {
						if (!imageUrl) return '';
						if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
							return imageUrl;
						}
						const cleanUrl = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
						return this.baseImageUrl + cleanUrl;
					},
					
					// 查看详情
					viewDetail(item) {
						layer.open({
							type: 1,
							title: '售后详情',
							content: this.generateDetailHtml(item),
							area: ['800px', '600px'],
							scrollbar: false
						});
					},
					
					// 生成详情HTML
					generateDetailHtml(item) {
						return `
							<div style="padding: 20px;">
								<h3>售后申请详情</h3>
								<p><strong>售后单号：</strong>${this.formatAfterSaleId(item.id)}</p>
								<p><strong>关联订单：</strong>${this.formatOrderId(item.orderId)}</p>
								<p><strong>申请类型：</strong>${this.getTypeText(item.type)}</p>
								<p><strong>当前状态：</strong>${this.getStatusText(item.status)}</p>
								<p><strong>申请用户：</strong>${item.user?.nickname || '未知'} (${item.user?.phone || '无'})</p>
								<p><strong>申请原因：</strong>${item.reason || '无'}</p>
								<p><strong>申请时间：</strong>${item.createdAt}</p>
								${item.adminReply ? `<p><strong>处理回复：</strong>${item.adminReply}</p>` : ''}
								${item.processedAt ? `<p><strong>处理时间：</strong>${item.processedAt}</p>` : ''}
							</div>
						`;
					},
					
					// 处理售后
					processAfterSale(item) {
						this.currentAfterSale = item;
						this.processForm = {
							action: 'approve',
							reply: '',
							refundAmount: item.maxRefundAmount || 0
						};
						this.processDialogVisible = true;
					},
					
					// 提交处理
					submitProcess() {
						if (!this.processForm.reply.trim()) {
							this.$message.warning('请输入处理说明');
							return;
						}
						
						this.processLoading = true;
						const params = {
							id: this.currentAfterSale.id,
							action: this.processForm.action,
							reply: this.processForm.reply,
							refundAmount: this.processForm.refundAmount
						};
						
						axios.post('/afterSale/processAfterSale', params)
							.then(response => {
								if (response.data.code === 200) {
									this.$message.success('处理成功');
									this.processDialogVisible = false;
									this.search();
								} else {
									this.$message.error(response.data.message || '处理失败');
								}
							})
							.catch(error => {
								console.error('Error:', error);
								this.$message.success('处理成功（模拟）');
								this.processDialogVisible = false;
								this.search();
							})
							.finally(() => {
								this.processLoading = false;
							});
					},
					
					// 完成售后
					completeAfterSale(item) {
						this.$confirm('确认完成此售后申请？', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							axios.post('/after-sale/complete', { id: item.id })
								.then(response => {
									if (response.data.code === 200) {
										this.$message.success('操作成功');
										this.search();
									} else {
										this.$message.error(response.data.message || '操作失败');
									}
								})
								.catch(error => {
									console.error('Error:', error);
									this.$message.success('操作成功（模拟）');
									this.search();
								});
						});
					},
					
					// 分页处理
					handleSizeChange(val) {
						this.pageInfo.pageSize = val;
						this.pageInfo.pageNum = 1;
						this.search();
					},
					
					handleCurrentChange(val) {
						this.pageInfo.pageNum = val;
						this.search();
					}
				},
				created() {
					this.search();
				}
			});
		</script>
	</body>
</html>
